package com.my.demo.controller;

import com.my.demo.pojo.Result;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author liangyuanshao
 * @date 2021/12/19 - 17:12
 */



@RestController
public class HeadUploadController {
  @PostMapping("/uploadHead")
  public Result uploadHead(@RequestParam("profilePicture") MultipartFile[] profilePicture,HttpSession session)
      throws IOException {
    System.out.println(profilePicture);
    Result result=new Result();
    result.setSuccess(false);
    result.setDetail(null);
    Integer userId= (Integer) session.getAttribute("id");
    if(userId==null){
      userId=1;
    }

    String fileName = profilePicture[0].getOriginalFilename();
    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
    System.out.println("头像名称：" + fileName + ",头像后缀：" + suffix);
    if ("jpg".equals(suffix) || "png".equals(suffix)|| "jpeg".equals(suffix)) {

      String path= System.getProperty("user.dir");
      profilePicture[0].transferTo(new File(path+"\\picture\\"+userId+".jpg"));
      System.out.println(path+"\\picture\\"+userId+".jpg");
      result.setSuccess(true);
      result.setMsg("头像上传成功");
    }else {
      result.setMsg("头像上传失败");
    }
    return result;
  }
}
